import type { BonusKeyType } from '../Deposit/Bonus.vue';
import type { AnZhuangPwaHuoDongXiangQing, HuanYingHuoDongXiangQing, ZhuCeHuoDongXiangQing } from '~/api/services/main.api';
import { useReadyAll } from './useReadyAll';
import { getMaxRateText, toBnInt, toBnVal, toDecimalPlaces, toRateText } from './utils';

function getBonusItemTitle(idx: number) {
  const numbers = [
    $t('kmEMsdyTbu6XfNvEp7dNl'),
    $t('fp_2z49_24TXxMvE0Kc2a'),
    $t('hDapbqObu083fjPCcVyl'),
    $t('l1Uz0oEfRy6KbB8hSH1Q'),
    $t('8ldSg8zAauQrrN3FFxczl'),
    $t('fEbyb8Tqmr4SoM1CJqLuh'),
    $t('b_1U8d7diQQpbK2udPvjq'),
    $t('ljx4o1wdXqAt6kLxoWm1o'),
    $t('dEyIx9JkLnGemiHs3T89'),
    $t('6wHtFdOVvwqmOLueKxK9'),
  ];
  return `${numbers[idx < 10 ? idx : idx % 10]}`;
}

function toConvert(
  val: Parameters<typeof bignumber>[0] | undefined,
  originalCurrency: string | undefined,
  targetCurrency: string | undefined,
) {
  const bnV = toBnVal(val);
  if (!originalCurrency || !targetCurrency || !bnV) {
    return bignumber(0);
  }
  return toBnVal(useCurrencyStore().convert(originalCurrency, bnV, targetCurrency)) || bignumber(0);
}

function toTimeInfo(data?: { boost_expire_second?: number; expire_second?: number }) {
  /** 促销活动到期秒数 */
  const boostExpireSecond = toBnInt(toBnVal(data?.boost_expire_second))?.toNumber() ?? 0;

  /** 存款奖金活动到期秒数 */
  const expireSecond = toBnInt(toBnVal(data?.expire_second))?.toNumber() ?? 0;

  /** 是否在促销活动时间内 */
  const isInBoostExpireSecond = boostExpireSecond > 0;

  /** 是否在存款奖金活动时间内 */
  const isInExpireSecond = expireSecond > 0;

  /** 是否在两个活动时间内 */
  const isInTime = isInBoostExpireSecond || isInExpireSecond;

  const nowDate = dayjs();

  /** 促销活动到期Date */
  const boostExpireDate = nowDate.add(isInBoostExpireSecond ? boostExpireSecond : 0, 'second');

  /** 存款奖金活动到期Date */
  const expireDate = nowDate.add(isInExpireSecond ? expireSecond : 0, 'second');

  return {
    boostExpireSecond,
    expireSecond,
    isInBoostExpireSecond,
    isInExpireSecond,
    isInTime,
    nowDate,
    boostExpireDate,
    expireDate,
  };
}

function toBonusesDetailList(
  list: HuanYingHuoDongXiangQing['bonuses_details'],
  timeInfo: ReturnType<typeof toTimeInfo>,
  currency: string,
) {
  const detailsList = (list || []).map((x) => {
    const bnUsd = toBnVal(x.deposit_amount) || bignumber(0);
    const { cryptoMap, fiatMap } = useCurrencyStore();
    const _C = toValue(fiatMap)?.[currency] ?? toValue(cryptoMap)?.[currency];
    const bnUsdPrice = toBnVal(_C?.usd_price);
    // 达到才送的金额
    const bnDepositAmount = bnUsdPrice ? toConvert(bnUsd, 'USD', currency) : bignumber(0);

    const bnBoostRate = toBnVal(x.deposit_boost_rate);

    const bnBonustRate = toBnVal(x.deposit_bonus_rate);

    // 送的比例
    const bnRate = timeInfo.isInBoostExpireSecond ? bnBoostRate : bnBonustRate;

    return {
      bnUsd,
      usdText: bnUsd.gt(0) ? `$${bnUsd.toFormat()}` : '',
      depositAmount: bnDepositAmount.toNumber(),
      bnDepositAmount,
      bnRate,
      rateText: toRateText(bnRate),
      bnBoostRate,
      // 促销比例文案
      boostRateText: toRateText(bnBoostRate),
      bnBonustRate,
      // 存款奖金比例文案
      bonustRateText: toRateText(bnBonustRate),
    };
  });

  return detailsList.sort((a, b) => a.depositAmount - b.depositAmount);
}

function toWagerDetail(x: HuanYingHuoDongXiangQing['wager_detail'], currency: string) {
  if (!x) {
    return null;
  }
  const bnRate = toBnVal(x.deposit_bet_rate);

  const bnUsdMinAmount = toBnVal(x.min_bet_amount) || bignumber(0);

  const bnUsdMaxAmount = toBnVal(x.max_bet_amount) || bignumber(0);

  return {
    currency,
    bnRate,
    rateText: bnRate?.gt(0) ? toRateText(bnRate) : '',
    bnUsdMinAmount,
    usdMinAmountText: bnUsdMinAmount.gt(0) ? `$${bnUsdMinAmount.toFormat()}` : '',
    bnMinAmount: toConvert(bnUsdMinAmount, 'USD', currency),
    bnUsdMaxAmount,
    usdMaxAmountText: bnUsdMaxAmount.gt(0) ? `$${bnUsdMaxAmount.toFormat()}` : '',
    bnMaxAmount: toConvert(bnUsdMaxAmount, 'USD', currency),
  };
}

function toBonusDetailData(data: HuanYingHuoDongXiangQing, currency: string) {
  const timeInfo = toTimeInfo(data);
  const bonusesDetails = toBonusesDetailList(data.bonuses_details || [], timeInfo, currency);

  const bnMaxUsd = toBnVal(data.deposit_max_bonus) || bignumber(0);

  const title = getBonusItemTitle(data.deposit_count - 1);

  const lastDetail = bonusesDetails.length ? bonusesDetails[bonusesDetails.length - 1] : null;
  const maxBoostRateText = getMaxRateText(bonusesDetails.map(x => x.bnBoostRate || bignumber(0))) || lastDetail?.boostRateText || '';
  const maxBonustRateText = getMaxRateText(bonusesDetails.map(x => x.bnBonustRate || bignumber(0))) || lastDetail?.bonustRateText || '';

  return {
    title, // 标题
    depositCount: data.deposit_count, // 充值次数
    rowkey: `${title}_${data.deposit_count}_${timeInfo.nowDate.valueOf()}`,
    currency,
    available: data.available,
    period: data.period || 0,
    wagerDetail: toWagerDetail(data.wager_detail, currency),
    timeInfo,
    bonusesDetails,
    lastDetail,
    maxInfo: {
      bnUsd: bnMaxUsd,
      usdText: bnMaxUsd.gt(0) ? `$${bnMaxUsd.toFormat()}` : '',
      bnAmount: toConvert(data.deposit_max_bonus, 'USD', currency),
      boostRateText: maxBoostRateText,
      bonustRateText: maxBonustRateText,
    },
    toDeposit: () => data.available && openDepositFn('welcome'),
  };
}

export type BonusDetailType = ReturnType<typeof toBonusDetailData>;

export function openDepositFn(checkedBonusKey?: BonusKeyType) {
  const authed = useAuthed();
  if (toValue(authed)) {
    globalPopups.wallet.open({ isDepositPage: true, checkedBonusKey });
  }
  else {
    globalPopups.sign.open?.({ view: 'signIn' });
  }
}

/** 充值活动信息 */
export function useWelcomeBonusInfo(
  currencyRef: ComputedRef<string>,
  withdrawAmountRef?: ComputedRef<string>,
) {
  const { depositReadyQry, refetchDepositReady } = useReadyAll();

  const getWelcomeBonusRef = computed(() => toValue(depositReadyQry?.data)?.welcome_bonus);

  const getAvailableRef = computed(() => getWelcomeBonusRef.value?.available);

  const getTimeInfoRef = computed(() => toTimeInfo(getWelcomeBonusRef.value));

  /** 奖金详情列表 */
  const getBonusesDetailsRef = computed(() => {
    const timeInfo = getTimeInfoRef.value;
    if (!getAvailableRef.value || !timeInfo.isInTime) {
      return [];
    }
    return toBonusesDetailList(getWelcomeBonusRef.value?.bonuses_details || [], timeInfo, currencyRef.value);
  });

  function findDetailToAmount(bnInputVal: ReturnType<typeof bignumber>) {
    if (!getAvailableRef.value || !getTimeInfoRef.value.isInTime || bnInputVal.lte(0)) {
      return null;
    }
    const list = getBonusesDetailsRef.value;
    let closest: GetArrayItemType<typeof list> | null = null;

    for (const item of list) {
      const val = item.bnDepositAmount;
      if (val.lte(0)) {
        continue;
      }
      if (val.eq(bnInputVal)) {
        return item;
      }
      if (val.lt(bnInputVal) && (!closest || val.gt(closest?.bnDepositAmount || 0))) {
        closest = item;
      }
    }
    return closest;
  }

  /** 额外金额 */
  const getExtraAmountRef = computed(() => {
    const bnInputVal = toBnVal(withdrawAmountRef?.value);
    if (!getTimeInfoRef.value.isInTime || !bnInputVal || !getAvailableRef.value) {
      return bignumber(0);
    }
    const bnMax = toConvert(getWelcomeBonusRef.value?.deposit_max_bonus, 'USD', currencyRef.value);
    const bnAmount = bnMax.gt(0) && bnInputVal.gt(bnMax) ? bnMax : bnInputVal;

    const bnRate = findDetailToAmount(bnInputVal)?.bnRate;

    return bnRate ? toBnInt(bnAmount.multipliedBy(bnRate)) : bignumber(0);
  });

  /** 额外金额说明 */
  const getExtraTipsRef = computed(() => {
    const wagerDetail = getWelcomeBonusRef.value?.wager_detail;

    const beforeBetRateText = toDecimalPlaces(toBnVal(toValue(depositReadyQry?.data)?.deposit_and_bet_rate))?.toFormat() ?? '';

    const afterBetRateText = toDecimalPlaces(toBnVal(wagerDetail?.deposit_bet_rate))?.toFormat() ?? '';

    const tips = `<span>${$t('gVaWcT3uri3n9Ry4baGg', {
      num1: `<span class="text-yellow-500 font-semibold mx-0.5">${beforeBetRateText}</span>`,
      num2: `<span class="text-yellow-500 font-semibold mx-0.5">${afterBetRateText}</span>`,
    })}</span>`;

    return beforeBetRateText && afterBetRateText && getAvailableRef.value ? tips : '';
  });

  /** BonusDetailData */
  const getBonusDetailDataRef = computed(() => getWelcomeBonusRef.value && getAvailableRef.value ? toBonusDetailData(getWelcomeBonusRef.value, currencyRef.value) : null);

  return {
    getWelcomeBonusRef,
    getAvailableRef,
    getTimeInfoRef,
    getBonusesDetailsRef,
    getExtraAmountRef,
    getExtraTipsRef,
    getBonusDetailDataRef,
    findDetailToAmount,
    refetchDepositReady,
  };
}

/** 欢迎活动列表信息 */
export function useActivityWelcomeBonus() {
  const { cryptoName } = storeToRefs(useCurrencyStore());

  const getCryptoNameRef = computed(() => cryptoName.value || '');

  const activityWelcomeBonusQry = useQuery({
    queryKey: [apis.apiActivityWelcomeBonus.id],
    queryFn: () => apis.apiActivityWelcomeBonus(void 0),
    refetchInterval: 30 * 1000,
  });

  const getBonusListRef = computed((): BonusDetailType[] => {
    const list = activityWelcomeBonusQry.data.value || [];
    return list.map(x => toBonusDetailData(x, getCryptoNameRef.value));
  });

  const getBoostItemRef = computed((): BonusDetailType | undefined => getBonusListRef.value.find(x => x.available && x.timeInfo.isInBoostExpireSecond) ?? void 0);

  return {
    getBonusListRef,
    getBoostItemRef,
    getCryptoNameRef,
    refetchActivity: activityWelcomeBonusQry.refetch,
  };
}

function toSignUpBonusData(data?: ZhuCeHuoDongXiangQing, currency?: string) {
  if (!data || !data?.available) {
    return;
  }
  const bnDepositUsd = toBnVal(data.deposit_amount) || bignumber(0);

  const bnAmountUsd = toBnVal(data.amount) || bignumber(0);

  const bnDepositMaxBonusUsd = toBnVal(data.deposit_max_bonus) || bignumber(0);

  const _currency = currency || data.currency;
  const { cryptoMap, fiatMap } = useCurrencyStore();
  const bnUsdPrice = toBnVal((fiatMap[_currency] ?? cryptoMap[_currency])?.usd_price);

  return {
    ...data,
    timeInfo: toTimeInfo(data),
    bnDepositUsd,
    depositUsdText: bnDepositUsd.gt(0) ? `$${bnDepositUsd.toFormat()}` : '',
    bnDepositAmount: bnUsdPrice ? toConvert(bnDepositUsd, data.currency, currency) : bignumber(0),
    bnAmountUsd,
    amountUsdText: bnAmountUsd.gt(0) ? `$${bnAmountUsd.toFormat()}` : '',
    bnAmount: bnUsdPrice ? toConvert(bnAmountUsd, data.currency, currency) : bignumber(0),
    bnDepositMaxBonusUsd,
    depositMaxBonusUsdText: bnDepositMaxBonusUsd.gt(0) ? `$${bnDepositMaxBonusUsd.toFormat()}` : '',
    bnDepositMaxBonus: bnUsdPrice ? toConvert(bnDepositMaxBonusUsd, data.currency, currency) : bignumber(0),
    wagerDetail: toWagerDetail(data.wager_detail, _currency),
  };
}

export type SignUpBonusDataType = ReturnType<typeof toSignUpBonusData>;

/** 注册活动信息 */
export function useSignUpBonusInfo(isRefetch = false, currencyRef?: ComputedRef<string>) {
  const { depositReadyQry, refetchDepositReady } = useReadyAll();

  isRefetch && refetchDepositReady();

  const getSignUpBonusDataRef = computed(() => {
    return toSignUpBonusData(toValue(depositReadyQry?.data)?.signup_bonus, currencyRef?.value);
  });

  return { getSignUpBonusDataRef };
}

function toPwaBonusData(data?: AnZhuangPwaHuoDongXiangQing, currency?: string) {
  if (!data || !data?.available) {
    return;
  }
  const bnAmountUsd = toBnVal(data.amount) || bignumber(0);

  const _currency = currency || data.currency;
  const { cryptoMap, fiatMap } = useCurrencyStore();
  const bnUsdPrice = toBnVal((fiatMap[_currency] ?? cryptoMap[_currency])?.usd_price);
  const bnAmount = bnUsdPrice ? toConvert(bnAmountUsd, data.currency, currency) : bignumber(0);

  return {
    ...data,
    timeInfo: toTimeInfo(data),
    bnAmountUsd,
    amountUsdText: bnAmountUsd.gt(0) ? `$${bnAmountUsd.toFormat()}` : '',
    bnAmount,
  };
}

export type PwaBonusDataType = ReturnType<typeof toPwaBonusData>;

/** 安装PWA送活动信息 */
export function usePwaBonusInfo(isRefetch = false, currencyRef?: ComputedRef<string>) {
  const { depositReadyQry, refetchDepositReady } = useReadyAll();

  isRefetch && refetchDepositReady();

  const getPwaBonusDataRef = computed(() => {
    return toPwaBonusData(toValue(depositReadyQry?.data)?.install_pwa_bonus, currencyRef?.value);
  });

  return { getPwaBonusDataRef };
}
